import { login, logout } from '@/api/login'
import md5 from 'js-md5'

const user = {
  state: {},

  mutations: {},

  actions: {
    // 用户名登录
    login({ commit }, userInfo) {
      const username = userInfo.username.trim()
      const password = md5(userInfo.password)
      return new Promise((resolve, reject) => {
        login(username, password, userInfo.captchaCode)
          .then(({ data }) => {
            if (data.code === 0) {
              sessionStorage.setItem('token', data.data.token)
              commit('SET_PAGES', data.data.pages)
              commit('SET_MODULES', data.data.modules)
              resolve(data)
            } else {
              reject(new Error(data.msg))
            }
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    // 登出
    logout({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout()
          .then(() => {
            resolve()
          })
          .catch(error => {
            reject(error)
          })
      })
    }
  }
}

export default user
